
import 'dart:convert';

import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/constants/call_back.dart';
import 'package:e_reception_flutter/media_library/media_library_index/bean/js_response_bean.dart';
import 'package:e_reception_flutter/media_library/media_library_index/bean/poster_diy_info_bean.dart';
import 'package:e_reception_flutter/media_library/media_library_index/pages/poster_settings_page.dart';
import 'package:e_reception_flutter/media_library/media_library_index/widgets/set_poster_content_dialog.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_matisse_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:matisse_android_plugin/export_matisse.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_permission_lib.dart';
import 'package:vg_base/vg_screen_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:webview_flutter/webview_flutter.dart';
import '../media_library_index_view_model.dart';

class EditPosterPage extends StatefulWidget {
  static const ROUTER = "EditPosterPage";

  final String url;
  final String hsn;
  final String id;
  final String intoflg;

  const EditPosterPage(
      {Key key,
        @required this.url,
        this.id,
        this.hsn,
        this.intoflg,
      })
      : assert(url != null, "currentItem must be not null");

  @override
  State<StatefulWidget> createState() => _EditPosterPageState();

  static Future<dynamic> navigatorPush(
      BuildContext context,
      String url,
      String id,
      String hsn,
      String intoflg,
      ) {
    return RouterUtils.routeForFutureResult(
        context,
        EditPosterPage(
          url: url,
          id: id,
          hsn: hsn,
          intoflg: intoflg,
        ),
        routeName: EditPosterPage.ROUTER
    );
  }
}

class _EditPosterPageState extends BaseState<EditPosterPage> {
  MediaLibraryIndexViewModel _viewModel;
  WebViewController _webViewController;
  //webview加载成功
  bool isUrlLoadComplete = false;
  JsResponseBean _imageJsResponseBean;
  JsResponseBean _contentJsResponseBean;

  @override
  void initState() {
    super.initState();
    MediaLibraryIndexViewModel.EMPTY_FLAG = false;
    _viewModel = MediaLibraryIndexViewModel(this);
    _viewModel.getPosterDiyInfo(context, widget?.id, widget?.intoflg);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      resizeToAvoidBottomPadding: false,
      resizeToAvoidBottomInset: false,
      body: Column(
          children:[
            _toTopBarWidget(),
            SizedBox(height: 10,),
            _toPlaceHolderWidget(),
          ]),
    );
  }


  Widget _toTopBarWidget() {
    return VgTopBarWidget(
      isShowBack: true,
      rightPadding: 15,
      rightWidget: _toSaveButtonWidget(),
    );
  }

  Widget _toSaveButtonWidget() {
    return CommonFixedHeightConfirmButtonWidget(
      isAlive: true,
      width: 48,
      height: 24,
      unSelectBgColor:
      ThemeRepository.getInstance().getTextEditHintColor_3A3F50(),
      selectedBgColor:
      ThemeRepository.getInstance().getPrimaryColor_1890FF(),
      unSelectTextStyle: TextStyle(
          color: VgColors.INPUT_BG_COLOR,
          fontSize: 12,
          fontWeight: FontWeight.w600),
      selectedTextStyle: TextStyle(
          color: Colors.white, fontSize: 12, fontWeight: FontWeight.w600),
      text: "保存",
      onTap: (){
        _save();
        // print("点击");
        // String msg = uploadBean?.checkVerify();
        // if(StringUtils.isEmpty(msg)){
        //   _viewModel.setBasicInfo(context, _uploadValueNotifier.value);
        //   return;
        // }
        // VgToastUtils.toast(context, msg);
      },
    );
  }



  ///加载中
  Widget _toPlaceHolderWidget() {
    return ValueListenableBuilder(
      valueListenable: _viewModel?.statusTypeValueNotifier,
      builder:
          (BuildContext context, PlaceHolderStatusType value, Widget child) {
        return VgPlaceHolderStatusWidget(
          loadingStatus: value == PlaceHolderStatusType.loading,
          loadingCustomWidget: Container(
            padding: EdgeInsets.only(
                bottom: 50 + ScreenUtils.getBottomBarH(context) + 15),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                CircularProgressIndicator(
                  strokeWidth: 2,
                ),
                SizedBox(
                  height: 10,
                ),
                Text(
                  "正在加载",
                  style: TextStyle(
                      color: ThemeRepository.getInstance()
                          .getTextBFC2CC_BFC2CC(),
                      fontSize: 10),
                )
              ],
            ),
          ),
          errorStatus: value == PlaceHolderStatusType.error,
          errorOnClick: () => _viewModel.getPosterDiyInfo(context, widget?.id, widget?.intoflg),
          loadingOnClick: () => _viewModel.getPosterDiyInfo(context, widget?.id, widget?.intoflg),
          child: child,
        );
      },
      child: _toInfoWidget(),
    );
  }

  Widget _toInfoWidget(){
    return ValueListenableBuilder(
        valueListenable: _viewModel?.diyInfoNotifier,
        builder: (BuildContext context,
            ComPicDiyBean picDiyBean, Widget child) {
          return _toWebViewWidget(picDiyBean);
        });
  }

  Widget _toWebViewWidget(ComPicDiyBean picDiyBean) {
    double maxHeight = ScreenUtils.screenH(context) -
        ScreenUtils.getStatusBarH(context) -
        ScreenUtils.getBottomBarH(context) - 44;
    double screenWidth = ScreenUtils.screenW(context) - 30;
    double width;
    double height;
    if (maxHeight / screenWidth <= 16 / 9) {
      width = maxHeight / (16 / 9);
      height = maxHeight;
    } else {
      width = screenWidth;
      height = screenWidth * (16 / 9);
    }
    print("屏幕宽： ${screenWidth}");
    print("屏幕高： ${maxHeight}");
    print("真实宽： ${width}");
    print("真实高： ${height}");
    String url = widget?.url??"";
    // String url = "http://etpic.we17.com/test/20210728165000_7761.html?downloadflg=01&name=%E8%94%9A%E6%9D%A5%E6%97%A0%E9%99%90%E5%9F%B9%E8%AE%AD%E5%93%A6&address=%E4%B8%B0%E5%8F%B0%E5%8C%BA%E6%90%9C%E5%AE%9D%E5%95%86%E5%8A%A1%E4%B8%AD%E5%BF%83%E5%B2%81&logo=http%3A%2F%2Fetpic.we17.com%2Ftest%2F20210520180047_2080.jpg&is_edit=01";
    if(picDiyBean != null && StringUtils.isNotEmpty(picDiyBean.diytext)){
      url = url + "&diyjson=${picDiyBean.diytext}";
    }
    print("url:$url");

    return Container(
      width: width,
      height: height,
      child: ClipRRect(
        borderRadius: BorderRadius.all(Radius.circular(4)),
        child: Stack(
          children: [
            Opacity(
              opacity: isUrlLoadComplete ? 1 : 0,
              child: WebView(
                initialUrl: url,
                javascriptMode: JavascriptMode.unrestricted,
                javascriptChannels: <JavascriptChannel>[
                  _clickImageOrTextChannel(context),
                  _getSaveContent(context),
                ].toSet(),
                onPageFinished: (String url) {
                  print("加载完成\n" + url);
                  setState(() {
                    isUrlLoadComplete = true;
                  });
                  // setState(() {
                  //   _isLoading = false;
                  //   setState(() {
                  //
                  //   });
                  // });
                },
                onWebViewCreated: (controller) {
                  _webViewController = controller;
                },
                // gestureRecognizers: Set()
                //   ..add(
                //     Factory<TapGestureRecognizer>(
                //           () => tapGestureRecognizer,
                //     ),
                //   ),
              ),
            ),
            Visibility(
              visible: !isUrlLoadComplete,
              child: Center(
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    CircularProgressIndicator(
                      strokeWidth: 2,
                      // valueColor:ColorTween(begin: Colors.white, end: Colors.red[900]).animate(null),
                      // backgroundColor:(topInfo?.PVCnt?.punchcnt ?? 0)==0? Colors.transparent: Colors.white,
                      // value: _value/190,
                    ),
                    SizedBox(
                      height: 10,
                    ),
                    Text(
                      "正在加载",
                      style: TextStyle(
                          color: ThemeRepository.getInstance()
                              .getTextBFC2CC_BFC2CC(),
                          fontSize: 10),
                    )
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  //改变图片或者文字
  _changeImageOrText(String type, String position, String content) {
    String js = "get_content('${type}'"+",'${position}'"+",'${content}')";
    print("_changeImageOrText:" + js);
    _webViewController?.evaluateJavascript(js);
  }

  //保存
  _save(){
    _webViewController?.evaluateJavascript('save_diy()');
  }


  //编辑图片或者文字
  JavascriptChannel _clickImageOrTextChannel(BuildContext context) {
    return JavascriptChannel(
        name: 'editContent',
        onMessageReceived: (JavascriptMessage message) {
          print("收到了点击图片/文字的js回调");
          print(message.message);
          Map map = json.decode(message.message);
          JsResponseBean jsResponseBean = JsResponseBean.fromMap(map);
          if(jsResponseBean != null){
            //点击图片
            if("02" == jsResponseBean.type){
              _imageJsResponseBean = jsResponseBean;
              _chooseSinglePicAndClip(jsResponseBean.scalex, jsResponseBean.scaley);
              return;
            }
            //点击文字
            if("01" == jsResponseBean.type){
              _contentJsResponseBean = jsResponseBean;
              SetPosterContentDialog.navigatorPushDialog(context,
                  content: _contentJsResponseBean?.content,
                  onConfirm: (content){
                    _changeImageOrText("01", _contentJsResponseBean.position, content);
                  });
              return;
            }
          }
        });
  }

  //获取要上传的信息
  JavascriptChannel _getSaveContent(BuildContext context) {
    return JavascriptChannel(
        name: 'saveDiyData',
        onMessageReceived: (JavascriptMessage message) {
          print("收到了diy信息的js回调");
          List<JsResponseBean> tempDiyList = List()..addAll(((json.decode(message.message) as List) ?? []).map((e){
            return JsResponseBean.fromMap(e);
          }));
          List<JsResponseBean> diyList = new List();
          String picurl = "";
          if(tempDiyList != null && tempDiyList.length > 0){
            tempDiyList.forEach((element) {
              if("04" != element.type){
                diyList.add(element);
              }else{
                picurl = element.content;
              }
            });
          }

          PosterSettingsPage.navigatorPush(context,
              diyJson: json.encode(diyList),
            id: widget?.id,
            intoflg: widget?.intoflg,
            picurl: picurl
          );

        });
  }

  void _chooseSinglePicAndClip(int scalex, int scaley) async {
    String fileUrl =
    await MatisseUtil.clipOneImage(context, scaleX: scalex, scaleY: scaley,
        onRequestPermission: (msg)async{
          bool result =
          await CommonConfirmCancelDialog.navigatorPushDialog(context,
            title: "提示",
            content: msg,
            cancelText: "取消",
            confirmText: "去授权",
          );
          if (result ?? false) {
            PermissionUtil.openAppSettings();
          }
        });
    if (fileUrl == null || fileUrl == "") {
      return null;
    }
    VgMatisseUploadUtils.uploadSingleImage(
        fileUrl,
        VgBaseCallback(onSuccess: (String netPic) {
          if (StringUtils.isNotEmpty(netPic)) {
            _changeImageOrText("02", _imageJsResponseBean.position, netPic);
          } else {
            VgToastUtils.toast(context, "图片上传失败");
          }
        }, onError: (String msg) {
          VgToastUtils.toast(context, msg);
        }));
  }

}
